// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// 扩展添加授权功能到HTTP应用程序管道中的方法
    /// Extension methods to add authorization capabilities to an HTTP application pipeline.
    /// </summary>
    public static class AuthorizationAppBuilderExtensions
    {
        /// <summary>
        /// 添加授权中间件
        /// Adds the <see cref="AuthorizationMiddleware"/> to the specified <see cref="IApplicationBuilder"/>, which enables authorization capabilities.
        /// <para>
        /// 当授权使用端点路由路由的资源时，这个调用必须出现在对app.UseRouting()和app.UseEndpoints(…)的调用之间，以便中间件能够正常工作。
        /// When authorizing a resource that is routed using endpoint routing, this call must appear between the calls to
        /// <c>app.UseRouting()</c> and <c>app.UseEndpoints(...)</c> for the middleware to function correctly.
        /// </para>
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
        /// <returns>A reference to <paramref name="app"/> after the operation has completed.</returns>
        public static IApplicationBuilder UseAuthorization(this IApplicationBuilder app)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            VerifyServicesRegistered(app);

            return app.UseMiddleware<AuthorizationMiddleware>();
        }

        // 验证服务已注册
        private static void VerifyServicesRegistered(IApplicationBuilder app)
        {
            // 验证在调用UseAuthorization之前调用了AddAuthorizationPolicy。
            //我们使用AuthorizationPolicyMarkerService来确保添加了所有的服务。
            // Verify that AddAuthorizationPolicy was called before calling UseAuthorization
            // We use the AuthorizationPolicyMarkerService to ensure all the services were added.
            if (app.ApplicationServices.GetService(typeof(AuthorizationPolicyMarkerService)) == null)
            {
                throw new InvalidOperationException(Resources.FormatException_UnableToFindServices(
                    nameof(IServiceCollection),
                    nameof(PolicyServiceCollectionExtensions.AddAuthorization),
                    "ConfigureServices(...)"));
            }
        }
    }
}
